package org.brownflat.watergate.service;

import org.apache.log4j.Logger;
import org.brownflat.watergate.dao.ConfigurationDAO;
import org.brownflat.watergate.domain.Configuration;
import org.brownflat.watergate.domain.ConfigurationKey;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;

/**
 * <p>&copy Rupert Jones 2012</p>
 *
 * @author rup
 *
 */
@Service
@Transactional
public class DefaultConfigurationService implements ConfigurationService, InitializingBean {

    private static final Logger LOG = Logger.getLogger(DefaultConfigurationService.class);

    @Autowired
    private ConfigurationDAO configurationDAO;

    @Override
    @PostConstruct
    public void initialise() {
        for(ConfigurationKey key : ConfigurationKey.values()) {
            Configuration configuration = configurationDAO.findByKey(key);
            if(configuration == null) {
                configurationDAO.createFor(key);
            }
        }
    }

    @Override
    public long getScanInterval() {
        Configuration configuration = configurationDAO.findByKey(ConfigurationKey.SCAN_INTERVAL_MILLISECONDS);
        return (Long)configuration.getValue();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        LOG.info("Runtime configuration values initialised.");
    }
}
